'use strict';
angular.module('nec-admin.user')
    .directive('usernameRepeatCheck', ['$q', '$timeout', 'userService', function($q, $timeout, userService){
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, elem, attr, ctrl){
                $timeout(function(){
                    var oldUsername;
                    if(typeof elem.val() !== 'undefined'){
                        oldUsername = elem.val();
                    }
                    ctrl.$asyncValidators.usernameRepeatCheck = function (modelValue) {
                        if (ctrl.$isEmpty(modelValue)) {
                            return $q.when();
                        }

                        var def = $q.defer();
                        if(modelValue === oldUsername){
                            def.resolve();
                        }
                        else{
                            userService.usernameRepeatCheck(modelValue).then(function(resp){
                                resp.data ? def.resolve() : def.reject();
                            }, function(){
                                def.reject();
                            });
                        }

                        return def.promise;
                    };
                },1000);
            }
        };
    }]);
